/**
 * DSP产品 对CAS服务器请求的应答接口处理.
 * cas 向DSP 发送的http处理
 * ----------------------------------------
 */

"use strict";

var radon		= require('radon')
	,include 	= radon.use('Include')
	,util		= include.util
	,getConfig 	= include.config
	,ModelDB 	= include.ModelDB
	,userModule = util.require('/lib/user.js')
	,sdk  		= require('./UserCenter');

var mod = include.app.extend({
	init: function(){
		this.Super('init',arguments);
		var self 		= this;
		self.$namespace	= radon.config('app.user_namespace');
		self.$sdk 		= new sdk(getConfig('uc.api'), {
			'getRight': self.onGetRight
			,'getAccountInfo': self.onGetAccountInfo
			,'logout': self.onLogout
			,'getCreateAccountUrl': self.onGetCreateAccountUrl
			,'onUCPrimaryChange': self.onUCPrimaryChange
			,'onUCPrimaryDel': self.onUCPrimaryDel
			,'onUCPrimaryRecover': self.onUCPrimaryRecover
			,'onUCEmployeeDel': self.onUCEmployeeDel
			,'onUCUserPWChange': self.onUCUserPWChange
			,'onUCUserInactive': self.onUCUserInactive
			,'onUCUserActive': self.onUCUserActive
			,'onUCAccountOwnerChange': self.onUCAccountOwnerChange
			,'onUCAuthorizationChange': self.onUCAuthorizationChange
			,'onUCAuthorizationAdd': self.onUCAuthorizationAdd
			,'onUCAuthorizationDel': self.onUCAuthorizationDel
			,'onUCUserAccountListChange': self.onUCUserAccountListChange
			,'onUCAccountAuthChange': self.onUCAccountAuthChange
		}, self);
	},
	getEvents: function(){
		return [
			['uc.comm',			this.dispatch]
			,['verifyTicket',	this.verifyTicketRequest]
			,['switchUser',		this.switchUserRequest]
			,['logoutCas',		this.logoutRequest]
			,['createAccount',	this.createAccountRequest]
			,['accountChange',	this.accountChangeRequest]
			,['switchList',		this.switchListRequest]
			,['getUserRights',	this.getUserRightsRequest]
			,['roleOption',		this.roleOptionRequest]
			,['primaryOption',	this.primaryOptionRequest]
			,['employeeOption',	this.employeeOptionRequest]
		];
	},
	switchUserRequest: function(req){
		return this.$sdk.switchUser(req.get());
	},
	verifyTicketRequest: function(req){
		return this.$sdk.verifyTicket(req.get('ticket'));
	},
	logoutRequest: function(req){
		return this.$sdk.logoutCas(req.get());
	},
	createAccountRequest: function(req){
		return this.$sdk.send('createAccount', req.get());
	},
	accountChangeRequest: function(req){
		return this.$sdk.send('accountChange', req.get());
	},
	switchListRequest: function(req){
		return this.$sdk.switchList(req.get());
	},
	getUserRightsRequest: function(req){
		return this.$sdk.getUserRights(req.get());
	},
	roleOptionRequest: function(req){
		return this.$sdk.roleOption(req.get());
	},
	primaryOptionRequest: function(req){
		return this.$sdk.primaryOption(req.get());
	},
	employeeOptionRequest: function(req){
		return this.$sdk.employeeOption(req.get());
	},
	dispatch: function*(req){
		var self = this;
		var data = req.get();

		return yield self.$sdk.emit({
			ts: data.get.ts
			,token: data.get.token
			,data: data.post.data
		});
	}
	,onGetCreateAccountUrl: util.generator(function*(data){
		var token = util.token(64);
		var db = ModelDB.model('Token');
		var record = new db();
		record.Token = token;
		record.Time = Date.now();
		record.Data = data;
		yield record.save();
		var url = getConfig('uc.create') + '?token='+ encodeURIComponent(token) +  '&userId=' + data.userId;
		return {data: url};
	})
	/*
	 data: [{
	 	code: 权限点代码
	 	parentCode: 父权限点代码
	 	readonly: 只读
	 	name: 权限点名称
	 	note: 权限点描述
	 }]
	 */
	,onGetRight: util.generator(function*(){
		var rightFunc =  yield include.require('/lib/dspRight').right;
		var right = yield include.flatRight(rightFunc);

		if(right){
			return {data:right};
		}
		else {
			radon.throw(11105);
		}
	})
	,onGetAccountInfo:  util.generator(function *(){
		var db = ModelDB.model('DspUser');
		var list = yield db.getAccountIds();
		var result = [];
		list.forEach(function(user){
			var email = user.Name ? ('[' + user.Name +']') : '';
			result.push({
				'accountId': user.UserId,
				'parentId': user.CreateUserId,
				'name': user.UserName + email
			});
		});

		return {data: result};
	})
	,onLogout: util.generator(function*(data){
		var self = this
			,i
			,sessions
			,userId = +data.userId
			,isPrimary = data.isPrimary;

		var res = radon.getContextData('response');
		if(!isPrimary) {
			sessions =  yield res.findSession(self.$namespace + '.' + 'login.userId', userId)
		}
		else {
			sessions =  yield res.findSession(self.$namespace + '.' + 'primaryId', userId)
		}

		var sess;
		for(i = 0; i < sessions.length; i++) {
			sess = sessions[i];
			userId = util.getProp(sess, 'data.' + self.$namespace + '.login.userId');
			res.send("SOCKET{U_" + userId + "}@MASTER:logout");
			yield self._ipc.setSession(sess.sid, self.$namespace, null);
		}

		return {message: '登出成功'};
	})
	//修改了账号对应UC账号
	,onUCAccountOwnerChange: util.generator(function*(data) {
		var id = data.id;
		var primaryId = data.user.userId;
		var User = ModelDB.model('DspUser');
		var user = yield User.getById(id);
		if(user && +primaryId){
			user.PrimaryId = +primaryId;
			yield user.save();
		}

		return {data: 'thx'};
	})
	// 权限变化事件
	,onUCAuthorizationChange: util.generator(function*(data){
		try{
			include.validate(data, {
				'userId': Number,
				'accountId': Number,
				'right': {type: Array, necessary: false}
			});
		}catch(e){
			radon.throw(10000300, ['onUCAuthorizationDel']);
		}

		var self = this;
		var res = radon.getContextData('response');
		var i, session, user;
		var sessions = yield res.findSession(self.$namespace + '.' + 'login.userId', data.userId);
		for(i = 0; i < sessions.length; i++) {
			session = util.getProp(sessions[i], 'data.' + self.$namespace);
			if(session.currentId === data.accountId){
				user = userModule.toSessionData(session, data.right);
				res.send("switchUser@MAIN:clear" ,{LoginId: data.userId});
				res.send("SOCKET{U_" + data.userId + "}@MASTER:authorizationChange", {'active': data.accountId, 'right': user.rights});
				yield self._ipc.setSession(sessions[i].sid, self.$namespace, user);
			}
		}
		return {data: 'thx'};
	})
	,onUCAuthorizationAdd: util.generator(function*(data){
		var userId = data.userId;
		var id = data.accountId;
		var right = data.right;
		var res = radon.getContextData('response');
		res.send("SOCKET{U_" + userId + "}@MASTER:user/switchListChange", {});
		return {data: 'thx'};
	})
	,onUCAuthorizationDel: util.generator(function*(data, res){
		var userId = data.userId;
		var id = data.accountId;
		var right = data.right;
		var res = radon.getContextData('response');
		res.send("SOCKET{U_" + userId + "}@MASTER:user/switchListChange", {});
		return {data: 'thx'};
	})
	,onUCPrimaryChange: function(){
		return {data: 'thx'};
	}
	,onUCPrimaryDel: function(){
		return {data: 'thx'};
	}
	,onUCPrimaryRecover: function(){
		return {data: 'thx'};
	}
	,onUCEmployeeDel: function(){
		return {data: 'thx'};
	}
	,onUCUserPWChange: function(){
		return {data: 'thx'};
	}
	,onUCUserInactive: function(){
		return {data: 'thx'};
	}
	,onUCUserActive: function(){
		return {data: 'thx'};
	}
	,onUCUserAccountListChange: function(){
		return {data: 'thx'};
	}
	,onUCAccountAuthChange: function*(data){
		let all = data.all;
		let some = data.some;

		let self = this;
		let res = radon.getContextData('response');
		let sessions = [];

		// 使用这些帐号的都需要更新权限
		if(all && all.length){
			for(let id of all){
				sessions = sessions.concat(yield res.findSession(self.$namespace + '.' + 'currentId', id));
			}
		}

		// 指定用户和帐号的都需要更新权限
		if(some && some.length){
			for(let item of some){
				for(let uid of item.uids){
					let userSessions = yield res.findSession(self.$namespace + '.' + 'loginId', uid);
					sessions = sessions.concat(userSessions.filter(s => {
						let id = util.getProp(s, `data.${self.$namespace}.currentId`);
						return !!~item.aids.indexOf(id);
					}));
				}
			}
		}

		let keys = [];
		let sessionMap = new Map();
		for(let session of sessions){
			let spaceData = util.getProp(session, `data.${self.$namespace}`);
			keys.push({
				uid: spaceData.loginId,
				aid: spaceData.currentId
			});
			sessionMap.set(`${spaceData.loginId}-${spaceData.currentId}`, session);
		}

		// 请求获取新权限
		let ret = yield self.$sdk.getUserRights({'keys': keys});
		if(ret.code){
			radon.throw(ret.code, ret.message);
		}
		for(let item of ret.data){
			let session	= sessionMap.get(`${item.uid}-${item.aid}`);
			if(session){
				res.send(`SOCKET\{L_${item.uid}\}@MASTER:authorizationChange`, {
					'active': item.aid,
					'right': item.rights
				});

				let spaceData = util.getProp(session, `data.${self.$namespace}`);
				let user = userModule.toSessionData(spaceData, item.rights);
				yield self._ipc.setSession(session.sid, self.$namespace, user);
			}
		}
		return {data: 'thx'};
	}
});

module.exports = mod;


